{{define "table/index.html"}}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <script src="/static/cdn/jquery-3.5.1/jquery.min.js"></script>
    <script src="/static/cdn/fecha-4.2.0/fecha.min.js"></script>
    <link rel="stylesheet" href="/static/cdn/layui-2.5.6/css/layui.css">
    <script src="/static/cdn/layui-2.5.6/layui.all.js"></script>
    <script type='text/javascript'>
        //默认长度
        function toFixed3(value) {
            if (value != null) {
                return value.toFixed(3)
            }
            return "-"
        }

        function formatColorValue(item, row) {
            var sty = "";
            if (item.ID == 0) {
                sty = 'style="color:#FF0000"';
            }
            return '<div class="tooltip-test" ' + sty + ' data-toggle="tooltip" title="' + formatItemTip(item) + '">' + item.Value.toFixed(3) + '</div>';
        }

        function formatIntValue(value, row) {
            return value;
        }

        function formatTimeMS(value, row, field) {
            return fecha.format(new Date(value), "YYYY/MM/DD HH:mm:ss");
        }

        function onTableToolbarEvent(obj, tableName, $table, primary) {
            switch (obj.event) {
                case 'export':
                    var checkStatus = table.checkStatus(tableName);
                    var ids = "";
                    checkStatus.data.forEach(function (row, index) {
                        ids += row[primary] + ",";
                    });
                    ids = ids.substr(0, ids.lastIndexOf(","))

                    var newUrl = "../TableExport/" + tableName + "?keys=" + ids;
                    location.href = newUrl
                    break;
                case 'clear':
                    var checkStatus = table.checkStatus(tableName);
                    if (checkStatus.data.length == 0) {
                        layer.confirm("是否清空'" + tableName + "'的数据?", function (index) {
                            $.ajax({
                                type: "post",
                                dataType: "json",
                                url: "/v1/table/TableDelete/" + tableName,
                                success: function (rsp) {
                                    layer.msg(rsp.msg);
                                    location.reload();
                                }
                            });
                            layer.close(index);
                        })
                    } else {
                        var ids = "";
                        checkStatus.data.forEach(function (row, index) {
                            ids += row[primary] + ",";
                        });
                        ids = ids.substr(0, ids.lastIndexOf(","))
                        layer.confirm("是否删除'" + tableName + "'指定的" + checkStatus.data.length + "行数据?", function (index) {
                            $.ajax({
                                type: "post",
                                dataType: "json",
                                url: "/v1/table/TableDelete/" + tableName + "?keys=" + ids,
                                success: function (rsp) {
                                    layer.msg(rsp.msg);
                                    location.reload();
                                }
                            });
                            layer.close(index);
                        })
                    }
                    break;
            }
        }

        function formatTime(value, row, field, format) {
            return fecha.format(new Date(value * 1000), format);
        }

        function formatValue(value, row, field, dig) {
            if (value == null) {
                return '-';
            }
            return value.toFixed(dig)
        }
        function renderUpload(tableName) {
            var upload = layui.upload;
            var element = layui.element;
            element.render('progress');
            var uploadInst = upload.render({
                elem: "div[lay-event='upload']",
                url: '../TableInsertOrUpdate/' + tableName,
                accept: 'file',
                auto: false,
                exts: 'csv|txt',
                choose: function (obj) {
                    uploadInst.upload();
                },
                before: function (obj) {
                    layer.open({
                        type: 1,
                        area: '400px',
                        title: false,
                        closeBtn: 0,
                        content: $('#progress_bar')
                    });
                },
                done: function (res, index, upload) {
                    layer.closeAll('page');
                    console.log(res);
                    debugger;
                    if (res.code == 200) {
                        location.reload();
                    }
                    layer.msg(res.msg);
                },
                error: function () {

                    layer.closeAll('page');
                    layer.msg("上传失败");
                },
                progress: function (n, elem) {
                    var percent = n + '%';
                    element.progress('progressBar', percent)
                }
            })
        }

        table = layui.table;
    </script>
    <title></title>
</head>

<body>
    <div style="display: none;" class="layui-progress layui-progress-big" lay-showpercent="true"
        lay-filter="progress_bar" id="progress_bar">
        <div class="layui-progress-bar" lay-percent="10%"></div>
    </div>
    <div id="app"></div>
    <script>
        var tableName = "";
        table = layui.table;
        //初始化页面
        function initApp(tab) {
            tableName = tab.Name;
            //添加表格
            var html = "<table id='table_" + tableName + "' lay-filter='table_" + tableName + "'> </table>\n";

            //添加工具栏
            var htmlToolbar = "";
            for (var i = 0; i < tab.Columns.length; i++) {
                column = tab.Columns[i];
                if (column.Search != null && column.Search) {
                    htmlToolbar += "    <div class='layui-inline'>&nbsp;" + column.Title + ":</div><div class='layui-inline'>\n";
                    htmlToolbar += "    <input class='layui-input' style='height:33px; width:150px;' placeholder='' id='search_" + column.Name + "' autocomplete='off'></div>\n";
                }
            }
            if (htmlToolbar.length > 0) {
                htmlToolbar = "<script type='text/html' id='toolbar_" + tableName + "'>" + htmlToolbar;
                htmlToolbar += "    <button class='layui-btn layui-btn-sm' lay-event='search_" + tableName + "'><i class='layui-icon layui-icon-search'></i></button>\n</" + "script>\n";
            }

            html += htmlToolbar;

            //添加脚本数据
            html += "<script type='text/javascript'>\n";
            html += "   document.title='" + tab.Title + "';\n";

            //定义搜索的变量
            html += "   var " + tableName + "_where='';\n";
            for (var i = 0; i < tab.Columns.length; i++) {
                column = tab.Columns[i];
                if (column.Search != null && column.Search) {
                    html += "   var search_" + column.Name + "='';\n";
                }
            }

            //设置页面标题
            html += "   var tableOption={\n";
            html += "      id:'" + tableName + "',\n";
            html += "      method:'post',\n\
        page:true,\n\
        defaultToolbar:['filter','print'],\n\
        limit:20,\n\
        limits:[10,20,50,100,200],\n\
        url:window.location,\n\
        cellMinWidth:50,\n\
        response:{\n\
        statusCode:200,//规定成功的状态码，默认：0\n\
      }\n";
            html += "      ,elem:'#table_" + tableName + "'\n";
            html += "      ,toolbar:'#toolbar_" + tableName + "'\n";
            html += "      ,where:{where:" + tableName + "_where}\n";
            html += "      ,done:function(res,curr,count){\n";
            for (var i = 0; i < tab.Columns.length; i++) {
                column = tab.Columns[i];
                if (column.Search != null && column.Search) {
                    html += "           $('#search_" + column.Name + "').val(search_" + column.Name + ")" + ";\n";
                }
            }
            html += "      }\n";

            //添加列信息
            html += "      ,cols:[[\n";
            var first = true;
            if (tab.HasCheckbox) {
                html += "           {type:'checkbox'}\n";
                first = false;
            }
            //循环增加字段信息
            for (var i = 0; i < tab.Columns.length; i++) {
                column = tab.Columns[i];
                if(column.Name == null || column.Name == ""){
                    continue
                }
                var field = "";
                if (first) {
                    first = false;
                    field = "           "
                } else {
                    field = "           ,"
                }
                field += "{field:'" + column.Name + "',title:'" + column.Title + "'";
                if (column.Align == null) {
                    field += ",align:'center'";
                } else {
                    field += ",align:'" + column.Align + "'";
                }
                if (column.Width != null) {
                    field += ",width:" + column.Width;
                } else if (tab.DefaultColumnWidth != null) {
                    field += ",width:" + tab.DefaultColumnWidth;
                }

                if (column.Name.indexOf(".") >= 0){
                    //templet: function (d) { return formatToFixed(d.Status6.theroyPowerGeneration, d) }
                    if (column.FormatFunc != null && column.FormatFunc != "") {
                        field += ",templet:function(d){return " + column.FormatFunc + "(d."+column.Name+",d)}";
                    }else{
                        field += ",templet:function(d){return d."+column.Name+"}";
                    } 
                }else{
                    if (column.FormatFunc != null && column.FormatFunc != "") {
                        field += ",templet:function(d){return " + column.FormatFunc + "(d."+column.Name+",d)}";
                    }                    
                }
                field += "}\n"
                html += field;
            };
            html += "       ]]\n"
            html += "   };\n"

            //添加按钮
            html += "   tableOption.defaultToolbar.unshift({title:'导出全部数据',layEvent:'export',icon:'layui-icon-download-circle'});\n\
   tableOption.defaultToolbar.unshift({title:'导入数据',layEvent:'upload',icon:'layui-icon-upload'});\n\
   tableOption.defaultToolbar.push({title:'清空数据',layEvent:'clear',icon:'layui-icon-delete'});\n";
            if (tab.HasRefresh) {
                html += "   tableOption.defaultToolbar.unshift({title:'刷新',layEvent:'refresh',icon:'layui-icon-refresh-3'});\n";
            }

            html += "   tableOption.height='full-20';\n";
            //渲染表格信息
            html += "   var $table_" + tableName + " = table.render(tableOption);\n";

            //设置事件
            html += "	table.on('toolbar(table_" + tableName + ")', function (obj) {\n";
            html += "		switch (obj.event) {\n";
            html += "		case 'search_" + tableName + "':\n";
            html += "			var where = {};\n";
            for (var i = 0; i < tab.Columns.length; i++) {
                column = tab.Columns[i];
                if (column.Search != null && column.Search) {
                    html += "			search_" + column.Name + "=$('#search_" + column.Name + "').val();\n";
                    html += "			where.search_" + column.Name + "=search_" + column.Name + ";\n";
                }
            }
            html += "			where.where=" + tableName + "_where;\n";
            html += "			$table_" + tableName + ".reload({where:where});\n";
            html += "			break;\n";
            html += "		case 'refresh':\n";
            html += "			$('.layui-laypage-btn').click()\n";
            html += "			break;\n";
            html += "		default:\n";
            html += "			onTableToolbarEvent(obj,'" + tableName + "',$table_" + tableName + ", '" + tab.Primary + "');\n";
            html += "			break;\n";
            html += "		}\n";
            html += "	})\n";

            html += "renderUpload('" + tableName + "')";

            html += "</" + "script>";
            console.log(html);
            $("#app").html(html);
        }
        $(function () {
            var url = window.location.href;
            var ss = url.split("/")
            if (ss.length < 1) {
                return
            }
            ss[ss.length - 2] = "GetJSON";
            url = ss.join("/")
            console.log(url);
            $.ajax({
                type: "get",
                dataType: "json",
                url: url,
                success: initApp
            });
        })
    </script>
</body>

</html>
{{end}}